<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑员工' : '添加员工'"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input v-model="formData.employeeName" placeholder="请输入员工姓名" maxlength="20" />
      </el-form-item>

      <el-form-item label="电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" maxlength="20" />
      </el-form-item>

      <el-form-item label="入职时间" prop="hireTime">
        <el-date-picker v-model="formData.hireTime" type="date" placeholder="请选择入职时间" style="width: 100%" />
      </el-form-item>

      <el-form-item label="员工状态" prop="employeeStatus">
        <el-select v-model="formData.employeeStatus" placeholder="请选择员工状态">
          <el-option label="在职" value="active" />
          <el-option label="离职" value="inactive" />
          <el-option label="试用期" value="probation" />
          <el-option label="停薪留职" value="suspended" />
        </el-select>
      </el-form-item>

      <el-descriptions v-if="isEdit" :column="2" border>
        <el-descriptions-item label="员工编号">{{ formData.employeeId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="企业编号">{{ formData.enterpriseId || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ isEdit ? '更新' : '添加' }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { employeeAPI } from '@/api/enterprise'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  employeeData: { type: Object, default: () => ({}) },
  enterpriseId: { type: Number, default: 1 }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.employeeData?.employeeId)

const formRef = ref()
const loading = ref(false)

const formData = reactive({
  employeeId: '',
  enterpriseId: '',
  employeeName: '',
  phone: '',
  hireTime: '',
  employeeStatus: 'active'
})

const formRules = {
  employeeName: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度 2-20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  hireTime: [
    { required: true, message: '请选择入职时间', trigger: 'change' }
  ],
  employeeStatus: [
    { required: true, message: '请选择员工状态', trigger: 'change' }
  ]
}

watch(visible, (val) => { if (val) initForm() })

function initForm() {
  if (isEdit.value) {
    Object.keys(formData).forEach((k) => { formData[k] = props.employeeData?.[k] ?? formData[k] })
    formData.enterpriseId = props.enterpriseId
  } else {
    Object.keys(formData).forEach((k) => { formData[k] = (k === 'employeeStatus') ? 'active' : '' })
    formData.enterpriseId = props.enterpriseId
  }
}

function handleClose() {
  visible.value = false
  formRef.value?.resetFields?.()
}

async function handleSubmit() {
  try {
    await formRef.value?.validate?.()
    loading.value = true
    
    console.log('开始提交员工数据:', formData)
    
    const submitData = {
      employeeName: formData.employeeName,
      phone: formData.phone,
      hireTime: formData.hireTime, // 前端使用hireTime，后端期望hireTime
      employeeStatus: formData.employeeStatus,
      position: formData.position || '',
      department: formData.department || ''
    }
    
    console.log('提交数据:', submitData)
    
    if (isEdit.value) {
      // 更新员工
      const result = await employeeAPI.updateEmployee(formData.employeeId, submitData)
      ElMessage.success('员工更新成功')
      
      // 返回更新后的员工数据
      const updatedEmployeeData = {
        employeeId: formData.employeeId,
        enterpriseId: formData.enterpriseId,
        employeeName: submitData.employeeName,
        phone: submitData.phone,
        hireTime: submitData.hireTime,
        employeeStatus: submitData.employeeStatus,
        position: submitData.position,
        department: submitData.department
      }
      emit('success', updatedEmployeeData)
    } else {
      // 创建员工
      submitData.enterpriseId = props.enterpriseId // 使用传入的企业ID
      const result = await employeeAPI.createEmployee(submitData)
      ElMessage.success('员工添加成功')
      
      // 确保返回的数据格式正确
      const employeeData = {
        employeeId: result.data?.employeeId || result.data?.employee_id,
        enterpriseId: props.enterpriseId,
        employeeName: submitData.employeeName,
        phone: submitData.phone,
        hireTime: submitData.hireTime,
        employeeStatus: submitData.employeeStatus,
        position: submitData.position,
        department: submitData.department
      }
      console.log('API成功，返回员工数据:', employeeData)
      emit('success', employeeData)
    }
    
    handleClose()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || (isEdit.value ? '更新失败' : '添加失败'))
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer { text-align: right; }
</style>
